import type { LoginRequest, RegisterRequest, ChangePasswordRequest, AuthResponse, ApiError, User } from '../types/auth';

const API_BASE_URL = 'https://server.illli.cc';

// 通用API请求函数
export async function apiRequest<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`;
  
  const config: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  };

  try {
    const response = await fetch(url, config);
    const data = await response.json();

    if (!response.ok) {
      throw data as ApiError;
    }

    return data;
  } catch (error) {
    if (error instanceof Error) {
      throw {
        error: {
          status: 500,
          name: 'NetworkError',
          message: error.message,
        },
      } as ApiError;
    }
    throw error;
  }
}

// 登录
export async function loginUser(loginData: LoginRequest): Promise<AuthResponse> {
  return apiRequest<AuthResponse>('/api/auth/local', {
    method: 'POST',
    body: JSON.stringify(loginData),
  });
}

// 注册
export async function registerUser(registerData: RegisterRequest): Promise<AuthResponse> {
  return apiRequest<AuthResponse>('/api/auth/local/register', {
    method: 'POST',
    body: JSON.stringify(registerData),
  });
}

// 修改密码
export async function changeUserPassword(
  passwordData: ChangePasswordRequest,
  token: string
): Promise<User> {
  return apiRequest<User>('/api/auth/change-password', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify(passwordData),
  });
}

// 获取当前用户信息
export async function getCurrentUser(token: string): Promise<User> {
  return apiRequest<User>('/api/users/me', {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });
}